package com.sywb.chuangyebao.view.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.InterestIndustryInfo;
import com.sywb.chuangyebao.bean.MessageNum;
import com.sywb.chuangyebao.bean.UserData;
import com.sywb.chuangyebao.bean.UserInfo;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.ListCheckActivity;
import com.sywb.chuangyebao.view.LoginActivity;
import com.sywb.chuangyebao.view.ManuscriptManagementActivity;
import com.sywb.chuangyebao.view.MyCommentActivity;
import com.sywb.chuangyebao.view.UserDataActivity;
import com.sywb.chuangyebao.view.UserFriendsActivity;
import com.sywb.chuangyebao.view.UserHistoryActivity;
import com.sywb.chuangyebao.view.UserIndexActivity;
import com.sywb.chuangyebao.view.UserMessageActivity;
import com.sywb.chuangyebao.view.UserSettingActivity;
import com.sywb.chuangyebao.view.WebActivity;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.utils.SharedUtils;

import java.util.List;

import butterknife.BindView;

/**
 * 个人中心
 */
public class UserFragment extends BaseStatisticsFragment {

    @BindView(R.id.iv_index)
    ImageView ivIndex;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.iv_label)
    ImageView ivLabel;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_user_type)
    TextView tvUserType;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.iv_sign)
    ImageView ivSign;
    @BindView(R.id.ll_my)
    LinearLayout llMy;
    @BindView(R.id.ll_index)
    LinearLayout llIndex;
    @BindView(R.id.ll_friends)
    LinearLayout llFriends;
    @BindView(R.id.ll_collect)
    LinearLayout llCollect;
    @BindView(R.id.ll_history)
    LinearLayout llHistory;
    @BindView(R.id.rl_my_shop)
    RelativeLayout rlMyShop;
    @BindView(R.id.tv_my_message)
    TextView tvMyMessage;
    @BindView(R.id.tv_my_message_unread)
    TextView tvMyMessageUnread;
    @BindView(R.id.rl_my_message)
    RelativeLayout rlMyMessage;
    @BindView(R.id.tv_my_answer)
    TextView tvMyAnswer;
    @BindView(R.id.tv_my_question)
    TextView tvMyQuestion;
    @BindView(R.id.rl_my_comment)
    RelativeLayout rlMyComment;
    @BindView(R.id.tv_my_comment_unread)
    TextView tvMyCommentUnread;
    @BindView(R.id.rl_my_video)
    RelativeLayout rlMyVideo;
    @BindView(R.id.rl_my_article)
    RelativeLayout rlMyArticle;
    @BindView(R.id.tv_my_feedback)
    TextView tvMyFeedback;
    @BindView(R.id.tv_sys_setting)
    TextView tvSysSetting;
    @BindView(R.id.tv_my_info_percent)
    TextView tvMyInfoPercent;
    @BindView(R.id.tv_my_info_tofinish)
    TextView tvMyInfoToFinish;
    @BindView(R.id.rl_my_info)
    RelativeLayout rlMyInfo;
    @BindView(R.id.rl_manuscript_management)
    RelativeLayout rlManuscriptManagement;
    @BindView(R.id.tv_manuscript_management_tofinish)
    TextView tvManuscriptManagementToFinish;
    @BindView(R.id.tv_my_magazine)
    TextView tvMyMagazine;

    private int uid;
    private String messageNumJson;

    /**
     * Fragment 实例
     */
    public static UserFragment newInstance(Object... pramars) {
        UserFragment fragment = new UserFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_my;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);
        ivIndex = (ImageView) getView(R.id.iv_index);
        ivAvatar = (ImageView) getView(R.id.iv_avatar);
        ivLabel = (ImageView) getView(R.id.iv_label);
        tvUsername = (TextView) getView(R.id.tv_username);
        tvUserType = (TextView) getView(R.id.tv_user_type);
        tvSign = (TextView) getView(R.id.tv_sign);
        ivSign = (ImageView) getView(R.id.iv_sign);
        llMy = (LinearLayout) getView(R.id.ll_my);
        llIndex = (LinearLayout) getView(R.id.ll_index);
        llFriends = (LinearLayout) getView(R.id.ll_friends);
        llCollect = (LinearLayout) getView(R.id.ll_collect);
        llHistory = (LinearLayout) getView(R.id.ll_history);
        rlMyShop = (RelativeLayout) getView(R.id.rl_my_shop);
        tvMyMessage = (TextView) getView(R.id.tv_my_message);
        tvMyMessageUnread = (TextView) getView(R.id.tv_my_message_unread);
        rlMyMessage = (RelativeLayout) getView(R.id.rl_my_message);
        tvMyAnswer = (TextView) getView(R.id.tv_my_answer);
        tvMyQuestion = (TextView) getView(R.id.tv_my_question);
        rlMyComment = (RelativeLayout) getView(R.id.rl_my_comment);
        tvMyCommentUnread = (TextView) getView(R.id.tv_my_comment_unread);
        rlMyVideo = (RelativeLayout) getView(R.id.rl_my_video);
        rlMyArticle = (RelativeLayout) getView(R.id.rl_my_article);
        tvMyFeedback = (TextView) getView(R.id.tv_my_feedback);
        tvSysSetting = (TextView) getView(R.id.tv_sys_setting);
        tvMyInfoPercent = (TextView) getView(R.id.tv_my_info_percent);
        tvMyInfoToFinish = (TextView) getView(R.id.tv_my_info_tofinish);
        rlMyInfo = (RelativeLayout) getView(R.id.rl_my_info);
        rlManuscriptManagement = (RelativeLayout) getView(R.id.rl_manuscript_management);
        tvManuscriptManagementToFinish = (TextView) getView(R.id.tv_manuscript_management_tofinish);
        tvMyMagazine = (TextView) getView(R.id.tv_my_magazine);
        setOnClick(llMy, llIndex, llFriends, llCollect, llHistory, rlMyShop, rlMyMessage, tvMyQuestion, rlMyComment, tvMyFeedback, tvSysSetting, rlMyInfo, rlManuscriptManagement, tvMyMagazine);

        getView(R.id.rl_my_answer).setOnClickListener(this);
        getView(R.id.tv_my_article).setOnClickListener(this);
        getView(R.id.tv_my_video).setOnClickListener(this);

        initView();
    }

    @Override
    public void initPresenter() {
        getUserInfo();
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.USERISLOGIN)})
    public void rxIsLogin(String isLogin) {
        Logger.e("收到登录状态改变广播：" + isLogin);
        initView();
        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
            getUserData();
            getMsgNum();
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.TABLE_USERINFO)})
    public void rxUserInfoChange(String tableName) {
        Logger.e("收到用户信息改变广播：" + tableName);
        initData();
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.TABLE_USERDATA)})
    public void rxUserDataChange(String tableName) {
        Logger.e("收到用户资料改变广播：" + tableName);
        initData();
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.TABLE_INTERESTINDUSTRY)})
    public void rxInterestinDustryChange(String tableName) {
        Logger.e("收到用户兴趣爱好改变广播：" + tableName);
        initData();
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.USERCHAT), @Tag(Constants.COMMENT_REPLY_CHANGE)})
    public void rxMsgNumChnage(String data) {
        getMsgNum();
    }

    private void initView() {
        updateMessageCount(0);
        updateAnswerCount(0);
        updateCommentCount(0);

        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
            ivLabel.setVisibility(View.VISIBLE);
            tvUserType.setVisibility(View.VISIBLE);
            tvSign.setVisibility(View.VISIBLE);
            ivSign.setVisibility(View.VISIBLE);
            tvUsername.setBackgroundColor(Color.TRANSPARENT);
            tvUsername.setPadding(0, 0, 0, 0);
            tvUsername.setTextSize(18);
            initData();
        } else {
            ivLabel.setVisibility(View.GONE);
            tvUserType.setVisibility(View.GONE);
            tvSign.setVisibility(View.GONE);
            ivSign.setVisibility(View.GONE);
            tvMyMessageUnread.setVisibility(View.GONE);
            tvMyCommentUnread.setVisibility(View.GONE);
            tvMyAnswer.setVisibility(View.GONE);
            tvMyInfoPercent.setVisibility(View.GONE);
            tvMyInfoToFinish.setVisibility(View.GONE);
            tvUsername.setText(R.string.login_now);
            tvUsername.setBackgroundResource(R.drawable.round_line_white_translate);
            tvUsername.setTextSize(14);
            int dp12 = getResources().getDimensionPixelSize(R.dimen.dp_12);
            int dp6 = getResources().getDimensionPixelSize(R.dimen.dp_6);
            tvUsername.setPadding(dp12, dp6, dp12, dp6);

            ivIndex.setImageResource(R.drawable.user_bg);
            ivAvatar.setImageResource(R.drawable.head_image);
        }
    }

    private void initData() {
        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
            String openID = SharedUtils.getString(Constants.USEROPENID, "");
            uid = Integer.valueOf(openID);
            if (!TextUtils.isEmpty(openID)) {
                UserInfo userInfo = DbManager.getInstance().queryById(openID, UserInfo.class);
                if (userInfo != null) {
                    if (mActivity != null) {
                        GlideUtils.getCircleImageToUrl(mActivity, userInfo.getShowAvatar(), ivAvatar);
                    }

                    tvUsername.setText(userInfo.getShowName());

                    if (!TextUtils.isEmpty(userInfo.brief_intro)) {
                        tvSign.setText(userInfo.brief_intro);
                    } else {
                        tvSign.setText("写点什么介绍一下自己吧！");
                    }

                    rlMyVideo.setVisibility(View.GONE);
                    rlMyArticle.setVisibility(View.GONE);
                    tvMyInfoPercent.setVisibility(View.GONE);
                    tvMyInfoToFinish.setVisibility(View.GONE);

                    int userRole = userInfo.getUserRole();
                    int defBgImg = 0;
                    if (userRole == Constants.USER_TYPE_NORMAL) {
                        ivLabel.setVisibility(View.GONE);
                        tvUserType.setVisibility(View.GONE);
                        defBgImg = R.drawable.user_bg;

                        UserData userData = DbManager.getInstance().queryById(openID, UserData.class);
                        int percent = computerUserInfoPercent(userInfo, userData);
                        if (percent < 100) {
                            tvMyInfoPercent.setVisibility(View.VISIBLE);
                            tvMyInfoToFinish.setVisibility(View.VISIBLE);
                            tvMyInfoPercent.setText(percent + "%");
                        }
                    } else {
                        switch (userRole) {
                            case Constants.USER_TYPE_PROJECT:
                                ivLabel.setImageResource(R.drawable.icon_project);
                                tvUserType.setText("项目号");
                                defBgImg = R.drawable.project_number_bg;

                                rlMyVideo.setVisibility(View.VISIBLE);
                                rlMyArticle.setVisibility(View.VISIBLE);
                                break;
                            case Constants.USER_TYPE_SERVICE:
                                ivLabel.setImageResource(R.drawable.icon_service);
                                tvUserType.setText("服务商");
                                defBgImg = R.drawable.provider_bg;

                                rlMyShop.setVisibility(View.VISIBLE);
                                break;
                            case Constants.USER_TYPE_TUTOR:
                                ivLabel.setImageResource(R.drawable.icon_teacher);
                                tvUserType.setText("导师");
                                defBgImg = R.drawable.tutor_bg;
                                break;
                            case Constants.USER_TYPE_V:
                                ivLabel.setImageResource(R.drawable.official_icon);
                                tvUserType.setText("官方号");
                                defBgImg = R.drawable.user_bg;
                                break;
                        }
                    }

                    if (!TextUtils.isEmpty(userInfo.bg_img) && mActivity != null) {
                        GlideUtils.getNormalIamgeToUrl(mActivity, userInfo.bg_img, ivIndex, defBgImg);
                    } else {
                        ivIndex.setImageResource(defBgImg);
                    }

                }
            } else {
                RxBus.get().post(Constants.HTTP_SSO_LOGIN, Constants.HTTP_SSO_LOGIN);
            }
        }
    }

    /**
     * 计算用户资料完善度：总共10项纳入计算，每一项累加10
     *
     * @param userinfo
     * @param userData
     * @return
     */
    private int computerUserInfoPercent(UserInfo userinfo, UserData userData) {
        int percent = 0;
        if (userinfo != null) {
            if (!TextUtils.isEmpty(userinfo.avatar_s)) {
                percent += 10;
            }

            if (!TextUtils.isEmpty(userinfo.nickname)) {
                percent += 10;
            }

            if (!TextUtils.isEmpty(userinfo.brief_intro)) {
                percent += 10;
            }

            if (!TextUtils.isEmpty(userinfo.mobile)) {
                percent += 10;
            }
        }

        if (userData != null) {
            if (userData.gender > 0) {
                percent += 10;
            }

            if (userData.birth_year > 0) {
                percent += 10;
            }

            if (!TextUtils.isEmpty(userData.area)) {
                percent += 10;
            }

            if (userData.chuangye_stage > 0) {
                percent += 10;
            }

            if (userData.investment_budget > 0) {
                percent += 10;
            }

            // 兴趣爱好
            List<InterestIndustryInfo> list = DbManager.getInstance().query(InterestIndustryInfo.class);
            for (InterestIndustryInfo info : list) {
                if (info.isChecked) {
                    percent += 10;
                    break;
                }
            }
        }

        return percent;
    }

    private void getUserInfo() {
        HttpUtils.getUserInfo(new HttpCallback<UserInfo>() {
            @Override
            public void onSuccess(UserInfo userInfo) {
                SharedUtils.put(Constants.USEROPENID, userInfo.uid);
                SharedUtils.put(Constants.USERREFRESHTOKEN, userInfo.refresh_token);
                SharedUtils.put(Constants.USERACCESSTOKEN, userInfo.access_token);
                SharedUtils.put(Constants.USERAUTHTOKEN, userInfo.token);
                SharedUtils.put(Constants.USERAUTHTOKENSIG, userInfo.token_sig);
                SharedUtils.put(Constants.HTTP_SSO_BIND, userInfo.mobile);

                DbManager.getInstance().save(userInfo);

                SharedUtils.put(Constants.USERMOBILEVERIFY, userInfo.mobile_verify == 1);
                SharedUtils.put(Constants.USERISLOGIN, true);

                getUserData();
                getMsgNum();
            }
        });
    }

//    private void refreshToken(long expires_time) {
//        long refreshTime = (System.currentTimeMillis() / 1000) + (3 * 24 * 60 * 60);
//        Logger.e("refreshTime:" + refreshTime + " userInfo.expires_time:" + expires_time);
//        if (expires_time < refreshTime) {
//            HttpUtils.refreshToken(refreshToken, new HttpCallback<UserToken>() {
//                @Override
//                public void onSuccess(UserToken userToken) {
//                    SharedUtils.put(Constants.USERACCESSTOKEN, userToken.access_token);
//                    refreshToken = userToken.refresh_token;
//                    getUserData();
//                }
//            });
//        } else {
//            getUserData();
//        }
//    }

    private void getUserData() {
        HttpUtils.getUserData(new HttpCallback<UserData>() {
            @Override
            public void onSuccess(UserData userData) {

                if (TextUtils.isEmpty(userData.uid)) {
                    userData.uid = SharedUtils.getString(Constants.USEROPENID);
                }

                if (userData.chuangye_stage == 0 && (userData.expert_in_field == null || userData.expert_in_field.size() == 0)) {
                    // 用户还没有创业数据

                    int period = SharedUtils.getInt(Constants.USERBUSINESSPERIOD, 0);

                    List<InterestIndustryInfo> list = DbManager.getInstance().query(InterestIndustryInfo.class);
                    StringBuilder goodAreaIds = new StringBuilder();
                    for (InterestIndustryInfo info : list) {
                        if (info.isChecked) {
                            goodAreaIds.append(info.categoryId).append(Constants.COMMA);
                        }
                    }
                    if (goodAreaIds.length() > 0) {
                        goodAreaIds.delete(goodAreaIds.length() - 1, goodAreaIds.length());
                    }

                    HttpUtils.goodatUpdate(period, goodAreaIds.toString(), 0, new HttpCallback<Object>(goodAreaIds.toString()) {
                        @Override
                        public void onSuccess(Object o) {
                        }

                        @Override
                        public void onError(String strMsg) {
                            super.onError(strMsg);
                        }
                    });

                } else {
                    SharedUtils.put(Constants.USERBUSINESSPERIOD, userData.chuangye_stage);
                    SparseIntArray sparseIntArray = new SparseIntArray();
                    if (userData.expert_in_field != null && userData.expert_in_field.size() > 0) {
                        for (int i = 0; i < userData.expert_in_field.size(); i++) {
                            sparseIntArray.put(i, userData.expert_in_field.get(i));
                        }
                    }
                    List<InterestIndustryInfo> list = DbManager.getInstance().query(InterestIndustryInfo.class);
                    for (InterestIndustryInfo info : list) {
                        info.isChecked = sparseIntArray.indexOfValue(info.categoryId) >= 0;
                    }
                    DbManager.getInstance().save(list);
                }
                DbManager.getInstance().save(userData);
                initData();
            }
        });
    }

    public void getMsgNum() {
        HttpUtils.getMyMsgNum(new HttpCallback<MessageNum>() {
            @Override
            public void onSuccess(MessageNum messageNums) {
                updateMessageCount(messageNums.total_num);
                updateAnswerCount(messageNums.wenda_num);
                updateCommentCount(messageNums.comment_num);
                messageNumJson = JSON.toJSONString(messageNums);
                RxBus.get().post(Constants.POST_MY_MSGNUM, messageNumJson);
            }

            @Override
            public void onError(String strMsg) {
                super.onError(strMsg);
                updateMessageCount(0);
                updateAnswerCount(0);
                updateCommentCount(0);
                messageNumJson = Constants.NULL;
                RxBus.get().post(Constants.POST_MY_MSGNUM, messageNumJson);
            }
        });
    }

    private void updateMessageCount(int unReadCount) {
        if (unReadCount == 0) {
            tvMyMessageUnread.setVisibility(View.GONE);
        } else {
            tvMyMessageUnread.setVisibility(View.VISIBLE);
            if (unReadCount > 99) {
                unReadCount = 99;
            }
            tvMyMessageUnread.setText(String.valueOf(unReadCount));
        }
    }

    private void updateAnswerCount(int answerCount) {
        if (answerCount == 0) {
            tvMyAnswer.setVisibility(View.GONE);
        } else {
            tvMyAnswer.setVisibility(View.VISIBLE);
            if (answerCount > 99) {
                answerCount = 99;
            }
            tvMyAnswer.setText("有" + String.valueOf(answerCount) + "个提问待回答");
        }
    }

    private void updateCommentCount(int commentCount) {
        commentCount = commentCount > 99 ? 99 : commentCount;
        tvMyCommentUnread.setText(String.valueOf(commentCount));
        tvMyCommentUnread.setVisibility(commentCount > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        if (!isCanClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.ll_my:
                advanceIfLogin(UserDataActivity.class);
                break;
            case R.id.ll_index://主页
                advanceIfLogin(UserIndexActivity.class, uid);
                break;
            case R.id.ll_friends://关注
                advanceIfLogin(UserFriendsActivity.class);
                break;
            case R.id.ll_collect://收藏
                advanceIfLogin(ListCheckActivity.class, getString(R.string.my_collect));
                break;
            case R.id.ll_history: // 历史
                advanceIfLogin(UserHistoryActivity.class);
                break;
            case R.id.rl_my_shop://我的店铺
                advanceIfLogin(UserFriendsActivity.class, 2);
                break;
            case R.id.rl_my_message://消息
                advanceIfLogin(UserMessageActivity.class, messageNumJson);
                break;
            case R.id.rl_my_answer://我的回答
                advanceIfLogin(UserFriendsActivity.class, 1);
                break;
            case R.id.tv_my_question://我的提问
                advanceIfLogin(ListCheckActivity.class, getString(R.string.my_question));
                break;
            case R.id.rl_my_comment://我的评论
                advanceIfLogin(MyCommentActivity.class);
                break;
            case R.id.tv_my_article: //我的文章
                advanceIfLogin(UserIndexActivity.class, uid, 1);
                break;
            case R.id.tv_my_video: //我的视频
                advanceIfLogin(UserIndexActivity.class, uid, 2);
                break;
            case R.id.tv_my_feedback:
                advanceIfLogin(ListCheckActivity.class, getString(R.string.my_feedback));
                break;
            case R.id.tv_sys_setting:
                advance(UserSettingActivity.class);
                break;
            case R.id.rl_my_info:
                advanceIfLogin(UserDataActivity.class);
                break;
            case R.id.rl_manuscript_management://稿件管理
                advanceIfLogin(ManuscriptManagementActivity.class);
                break;
            case R.id.tv_my_magazine:
                advance(WebActivity.class, "", "https://at.umeng.com/aaemGb");
                break;
        }
    }

    private void advanceIfLogin(Class<?> cls, Object... params) {
        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
            advance(cls, params);
        } else {
            advance(LoginActivity.class);
        }
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

}
